<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
var echarts = require('echarts/lib/echarts')
// 引入 ECharts 主模块
require('echarts/lib/chart/pie')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
// require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { themeColor } from '@/assets/echarts/theme'

export default {
  name: 'EqpCodeEcharts',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '90%'
    },
    alarmCodeDate: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    alarmCodeList: function() {
      return this.alarmCodeDate.map(v => {
        return {
          value: v.count,
          name: v.alarmType
        }
      })
    }
  },
  watch: {
    alarmCodeDate: {
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'themeColor')
      this.chart.setOption({
        color: themeColor,
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '报警代码',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: true,
            top: '10%',
            emphasis: {
              label: {
                show: true
              }
            },
            data: this.alarmCodeList
          }
        ]
      })
    }
  }
}
</script>
